
import config from 'config';
import { resolve } from 'path';
import schema from 'async-validator';
import { AppContext } from 'ROOT/interface/App';

import KLineHistoryService from './KLineHistory.service';
import { binanceCommon } from 'ROOT/binance/BinanceCommon';
import { runWorker, transformToCSV } from 'ROOT/utils';
import { toPeriodData } from './kline.worker';

/**
 * 查询单个或者多个
 */
export const get = async (ctx: AppContext) => {
    const { start, end, symbol, period } = ctx.request.query;
    const validator = new schema({
        start: {
            type: "string",
            required: true,
        },
        end: {
            type: "string",
            required: true,
        },
        symbol: {
            type: "string",
            required: true,
        },
        period: {
            type: "string",
        },
    });
    try {
        await validator.validate({ start, end, symbol });
    } catch ({ errors, fields }) {
        ctx.sendError({errors});
        return;
    }
    try {
        const history = await KLineHistoryService.find({
            start: Number(start),
            end: Number(end),
            symbol: (symbol as string).toLowerCase()
        });

        const data = await runWorker<typeof toPeriodData>(resolve(__dirname, './kline.worker.ts'), {history, period})
        ctx.sendSuccess({data: data});
    } catch (error) {
 
        ctx.sendError({message: error.message});
    }
}

/**
 * 查kline
 */
 export const getCandles = async (ctx: AppContext) => {
    const { start, end, symbol } = ctx.request.query;
    const validator = new schema({
        start: {
            type: "string",
            required: true,
        },
        end: {
            type: "string",
            required: true,
        },
        symbol: {
            type: "string",
            required: true,
        }
    });
    try {
        await validator.validate({ start, end, symbol });
    } catch ({ errors, fields }) {
        ctx.sendError({errors});
        return;
    }
    try {
        const result = await binanceCommon.getCandles({
            symbol: symbol as string,
            startTime: Number(start),
            endTime: Number(end),
            interval: '15m'
        })
        ctx.sendSuccess({data: result});
    } catch (error) {
 
        ctx.sendError({message: error});
    }
}
/**
 * 新建
 */
export const create = async (ctx: AppContext) => {
    const data = ctx.request.body as any;
    const validator = new schema({
        buy: {
            type: "boolean",
            required: true,
        },
        sell: {
            type: "string",
            required: true,
        },
        symbol: {
            type: "string",
            required: true,
        },
        time: {
            type: "date",
            required: true,
        },
    });
    try {
        await validator.validate(data);
    } catch ({ errors, fields }) {
        ctx.sendError({errors});
        return;
    }
    try {
        let res;
        if (data.title) {
            res = await KLineHistoryService.create(data);
        } else {
            ctx.sendError({message: '格式有误'});
            return;
        }
        ctx.sendSuccess({
            data: res
        });

    } catch (error) {
        ctx.sendError({message: error});
    }
}


export const batchUpdate = async (ctx: AppContext) => {
    const { data, symbol } = ctx.request.body as Record<string, any>;
    const validator = new schema({
        data: {
            type: "array",
            required: true,
        },
        symbol: {
            type: "string",
            required: true,
        }
    });
    try {
        await validator.validate({ data, symbol });
    } catch ({ errors, fields }) {
        ctx.sendError({errors});
        return;
    }
    try {
        const res = await KLineHistoryService.batchUpdate(data);

        ctx.sendSuccess({});
    } catch (error) {
 
        ctx.sendError({message: error});
    }
}

export const fillSymbolMissData = async (ctx: AppContext) => {
    const data = ctx.request.body as Record<string, any>;
    const validator = new schema({
        symbol: {
            type: "string",
            required: true,
        },
        start: {
            type: "string",
            required: true,
        },
        end: {
            type: "string",
            required: true,
        }
    });
    try {
        await validator.validate(data);
    } catch ({ errors, fields }) {
        ctx.sendError({errors});
        return;
    }
    try {
        KLineHistoryService.fillMissData(data.symbol, new Date(data.start), new Date(data.end), '15m');
        ctx.sendSuccess({});
    } catch (error) {
        ctx.sendError({message: error.message});
    }
}

export const syncKLineData = async (ctx: AppContext) => {
    const data = ctx.request.query as Record<string, any>;
    const validator = new schema({
        symbol: {
            type: "string",
            required: true,
        },
        // start: {
        //     type: "string",
        // },
        // end: {
        //     type: "string",
        // }
    });

    try {
        KLineHistoryService.syncKLineData(data.symbol, new Date(data.start), new Date(data.end), '15m');
        ctx.sendSuccess({});
    } catch (error) {
  
        ctx.sendError({message: error.message});
    }
}
